package com.lsf.studentmanagerup.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 李树飞
 */
@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //判断session里面是否有用户信息，有则放行
        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        HttpSession httpSession = httpServletRequest.getSession();
        Object user = httpSession.getAttribute("user");

        //根据路径信息判断
        String servletPath = httpServletRequest.getServletPath();
        if (null == user && !servletPath.contains("login")) {
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        } else if (null != user && servletPath.contains("login")){
            req.getRequestDispatcher("main").forward(req,resp);
        } else {
            chain.doFilter(req, resp);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
